<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of FormPostEvent
 *
 * @author tuancasi
 */
class FormPostEvent extends CWidget {

    //put your code here
    public function run() {
	$eventModel = new Event();

	if (isset($_POST['ajax']) && $_POST['ajax'] == "event-form") {
	    echo CActiveForm::validate($eventModel);
	    Yii::app()->end();
	}

	if (isset($_POST['create-event'])) {
	    $eventModel->attributes = $_POST['Event'];
	    $eventModel->start = date('Y-m-d', strtotime($_POST['Event']['start']));
	    $eventModel->status = Event::STATUS_PENDING;
	    $eventModel->save();
	    $priceEvent = floatval(settings()->get("post_price", "event"));
	    $this->_redirectPaypal($eventModel, $priceEvent);
	}
	$this->render('formPostEvent', array("eventModel" => $eventModel));
    }

    /**
     * pay with paypal
     */
    private function _redirectPaypal($model, $price, $params = array()) {
	$paymentInfo = array();
	$paymentInfo['Order']['theTotal'] = $price;
	$paymentInfo['Order']['description'] = 'Register an event';
	$paymentInfo['Order']['quantity'] = '1';

	// call paypal
	$result = Yii::app()->Paypal->SetExpressCheckout($paymentInfo);
	//Detect Errors
	if (!Yii::app()->Paypal->isCallSucceeded($result)) {
	    if (Yii::app()->Paypal->apiLive === true) {
		//Live mode basic error message
		$error = 'We were unable to process your request. Please try again later';
	    } else {
		//Sandbox output the actual error message to dive in.
		$error = $result['L_LONGMESSAGE0'];
	    }
	    echo $error;
	    Yii::app()->end();
	} else {
	    // send user to paypal
	    $token = urldecode($result["TOKEN"]);
	    $payPalURL = Yii::app()->Paypal->paypalUrl . $token;

	    //add new invoice
	    $invoice = new Invoice;
	    $invoice->attributes = array(
		'model' => Invoice::MODEL_EVENT,
		'model_id' => $model->id, //id event
		'payment_method' => 'paypal',
		'payment_code' => $token,
		'status' => Invoice::STATUS_PENDING,
		'params' => CJSON::encode($params),
		'create_by' => user()->id,
		'total' => $price
	    );

	    if ($invoice->save()) {
		Yii::app()->controller->redirect($payPalURL);
	    } else {
		die('An error occured, please try again!');
	    }
	}
    }

}
